// App Root
var appPath = getAppPath();

// 是否延迟加载
var lazy = false;

// Datagrid ID
var datagrid_id = "#pageGrid";

// Datagrid URL参数
var datagrid_url = appPath+'/cms/page_list.do';

// Dialog ID
var dialog_id = "#addPageDlg";

// Form ID
var form_id = "#addPageForm";

/**
 * jQuery加载事件
 */
$(function(){
	// 初始化Datagrid
	initPlugin();
});

/**
 * 控件初始化方法
 */
function initPlugin() {
	$(datagrid_id).datagrid({
		url: lazy? '' : datagrid_url,
		height: "full",
		striped: true,
		remoteSort:false,
		queryParams: getQueryParam(),
		idField:'pageId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'pageId',title:'操作',width:40,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  //var dataStr = JSON.stringify(rowData); // 最好注释掉此行代码
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		]],
		columns:[[
		      {field:'pageName',title:'页面名称',width:200,align:'left',sortable:true},
		      {field:'htmlFileName',title:'HTML文件名称',width:200,align:'left',
		    	  formatter:function(value){
		    		  return '<span class="tommy-cell">' + (value? (value + ".html") : "暂无") + '</span>';
		    	  }
		      },
		      {field:'remark',title:'备注',width:240,align:'left'},
		      {field:'ctl',title:'控制区',width:85,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    		  var ctlHtml = '<span><a href="javascript: void(0);" onclick="generateHtml('+rowIndex+', this);">静态生成</a></span>';
		    		  ctlHtml += '<span style="display:none;"><img src=' + appPath + '/js/lib/jquery-easyui/themes/default/images/loading.gif align="left"/>' + '正在生成...</span>';		    		  
		    		  return ctlHtml;
		    	  }
		      }
		 ]],
		 pagination:true,
		 rownumbers:true,
		 onLoadSuccess: function() {
			 uncheckAll(this);
			 changeTipInfo("tommy-cell");
		 },
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},'-',{
				id:'btndelMu',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					deleteData();
				}
			}]
	});
	if (lazy)
		$(datagrid_id).datagrid('options').url = datagrid_url;
}

/**
 * 控件展现方法
 */
function showPlugin() {
	if (lazy) {
		initPlugin();
		lazy = false;
	}		
}

/**
 * 展现编辑页面
 * @param {} rowData
 */
function showEdit(rowIndex){
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	$(form_id).form('clear');
	$(form_id).form('load',rowData);
	
	$("#submitType").val("update");
	$(dialog_id).window({
			title:'编辑页面',
			iconCls:'icon-edit',
			modal: true,
			shadow: true,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');
}

/**
 * 提交数据（包括增加，修改）
 */
function doPostData(){
	$("#pageName").val($.trim($("#pageName").val()));
	$("#htmlFileName").val($.trim($("#htmlFileName").val()));
	
	if(!$(form_id).form('validate')){
		return ;
	}
	
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	var subData = $(form_id);  
    var pageinfo = subData.serialize();    
    
    $.loading(true);
    
    $.ajax({
		url:appPath+'/cms/page_'+type + '.do',
		type:"post",
		data:pageinfo,
		success:function(data){
			$.loading(false);
			if(data == "error"){
				$.messager.alert('提示信息','该页面名称已存在，请更换其它！','info');
			}else{
				doReload(type);
				closeWindow();
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，请求失败，'+textStatus,'error');
		}
	});
}

/**
 * 删除数据
 */
function deleteData() {
	var selections = $(datagrid_id).datagrid('getSelections');
	if(selections == null || selections == ''){
		$.messager.alert('提示信息','请选择要删除的数据','info');
		return ;
	}else{
		$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
			if(r){
				var ids = '';
				for(var i=0;i<selections.length;i++){
					ids += selections[i].pageId+',';
				}
				ids = ids.substring(0,ids.lastIndexOf(','));
				
				$.loading(true);
				$.ajax({
					url:appPath+'/cms/page_delMulti.do',
					data:{multi_id:ids},
					success:function(data){
						$.loading(false);
						if(data!='ok'){
							$.messager.alert('提示信息','页面有相关联的模版信息，不能删除！','info');
						}else{
							doReload('delete');
						}
					},
					error:function(XMLHttpRequest, textStatus, errorThrown){
						$.loading(false);
						$.messager.alert('提示信息','抱歉，请求失败，'+textStatus,'error');
					}
				});		
			}
		});
	}
}

/**
 * 关闭对话框
 */
function closeWindow(){
	$(dialog_id).window('close');
}

/**
 * 展现增加页面
 */
function showAdd(){
	$(form_id).form('clear');
	$("#submitType").val("save");
	$(dialog_id).window({
		title:'增加页面',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');	
}

/**
 * 获取请求信息
 * @return {}
 */
function getQueryParam(){
	var submitObject = new Object();
	submitObject.pageName = $.trim($('#queryPageName').val());
	return submitObject;
}

/**
 * 查询数据
 */
function doQuery(){
	showPlugin();
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('load',getQueryParam());
}

/**
 * 重载grid，取消全选
 */
function doReload(type){
	var ops = $(datagrid_id).datagrid('getPager').pagination("options");
	if(type == "save"){
		var pn = Math.floor(ops.total/ops.pageSize)+1;
		$(datagrid_id).datagrid('getPager').pagination({pageNumber:pn});
		$(datagrid_id).datagrid('options').pageNumber = pn;
	}else if(type == "delete"){
		if($(datagrid_id).datagrid('getRows').length == $(datagrid_id).datagrid('getSelections').length){
			var pn ;
			var pnt = Math.ceil(ops.total/ops.pageSize);
			var pm = ops.pageNumber;
			if(pnt == (pm-1)){
				pn = pnt ;
			}else{
				pn = pm
			}
			$(datagrid_id).datagrid('getPager').pagination({pageNumber:(pn==0?1:pn)});
			$(datagrid_id).datagrid('options').pageNumber = (pn==0?1:pn);
		}
	}
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('reload');
}

